package com.shisan.tingshu.album.receiver;

import com.alibaba.fastjson.JSONObject;
import com.shisan.tingshu.album.service.MqOpsService;
import com.shisan.tingshu.common.execption.ShisanException;
import com.shisan.tingshu.common.rabbit.constant.MqConst;
import com.shisan.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Component
@Slf4j
public class AlbumInfoListener {


    @Autowired
    private MqOpsService mqOpsService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE))
    @SneakyThrows
    public void listenTrackStatTypeUpdate(String content, Message message, Channel channel) {

        // 判断消息是否存在
        if (StringUtils.isEmpty(content)) {
            // 消息不存在，直接返回
            return;
        }
        // 处理消息
        TrackStatMqVo trackStatMqVo = JSONObject.parseObject(content, TrackStatMqVo.class);
        // 消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.trackStatTypeUpdate(trackStatMqVo);
            // 手动应答消息（若不应答，消息会一直存在队列中）
            channel.basicAck(deliveryTag, false);
        } catch (ShisanException e) {
            String msgRetryKey = "msg:retry:" + trackStatMqVo.getBusinessNo(); // 业务去重的编号
            Long count = redisTemplate.opsForValue().increment(msgRetryKey);
            // 三次重试
            if (count >= 3) { // 不能重试
                log.error("消息重试{}次失败，异常：{}", count, e.getMessage());
                channel.basicNack(deliveryTag, false, false); // 最后一个参数为true，表示不重新入队
                redisTemplate.delete(msgRetryKey); // 删除计数器
            } else {
                log.error("消息第{}次重试", count);
                channel.basicNack(deliveryTag, false, true); // 最后一个参数为false，表示重新入队
            }
        } catch (Exception e) {
            log.error("网络故障导致手动应答消息失败，异常：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }

    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_STAT_UPDATE, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            key = MqConst.ROUTING_ALBUM_STAT_UPDATE))
    @SneakyThrows
    public void listenAlbumStatTypeUpdate(String content, Message message, Channel channel) {

        // 1.判断消息是否存在
        if (StringUtils.isEmpty(content)) {
            return;  // 不用消费
        }
        JSONObject jsonObject = JSONObject.parseObject(content, JSONObject.class);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        // 2.消费消息
        mqOpsService.albumStatTypeUpdate(jsonObject);
        // 3.手动应答消息（将消息从队列中删除掉）
        channel.basicAck(deliveryTag, false);
    }
}